package com.caiyi.financial.nirvana.sms.gateway.sgip.message.body;

import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPMessageTool;
import com.caiyi.financial.nirvana.sms.gateway.sgip.message.SGIPBody;
import io.netty.buffer.ByteBuf;

/**
 * 请求连接消息体
 */
public class SGIPBind extends SGIPBody {

    //登录类型
    private byte longinType;

    //企业代码
    private String spId;

    //SP的密码
    private String password;

    public SGIPBind() {
        super();
    }

    /**
     * 构造函数
     *
     * @param spId
     * @param password
     */
    public SGIPBind(String spId, String password) {
        super();
        if (spId == null || spId.length() > 16) {
            throw new IllegalArgumentException("企业代码不能超过16位");
        }
        if (password == null) {
            throw new IllegalArgumentException("密码不能为空");
        }
        this.longinType = 1;
        this.spId = spId.intern();
        this.password = password.intern();
    }

    /**
     * 注册消息体编码
     */
    @Override
    public int encode(ByteBuf buffer) {
        int length = 0;
        //登录类型
        buffer.writeByte(longinType);
        length += 1;
        //登录名
        buffer.writeBytes(spId.getBytes());
        buffer.writeZero(16 - spId.getBytes().length);
        length += 16;
        //密码
        buffer.writeBytes(password.getBytes());
        buffer.writeZero(16 - password.getBytes().length);
        length += 16;
        //8位保留位
        buffer.writeZero(8);
        length += 8;
        return length;
    }


    @Override
    public SGIPBody decode(ByteBuf buffer) {

        this.longinType = buffer.readByte();

        //16字节登录名
        byte[] temp = new byte[16];
        buffer.readBytes(temp);
        temp = CMPPMessageTool.trimStringBufferRightZeros(temp);
        this.spId = new String(temp).intern();

        //16字节密码
        temp = new byte[16];
        buffer.readBytes(temp);
        temp = CMPPMessageTool.trimStringBufferRightZeros(temp);
        this.password = new String(temp).intern();

        //8位保留位
        buffer.readBytes(8);
        return this;
    }

    public String getSpId() {
        return spId;
    }


    public String getPassword() {
        return password;
    }


    public String toString() {
        return spId + "," + password;
    }
}
